<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */

namespace MoChat\App\Client\Logic;

use GuzzleHttp\Psr7\Query;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use MoChat\App\Client\Contract\ClientContract;

/**
 * 会员列表.
 *
 * Class IndexLogic
 */
class IndexLogic
{
    /**
     * @Inject
     * @var ClientContract
     */
    protected $clientService;


    /**
     * 成员列表.
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function handle(array $params): array
    {
        //返回的数据格式
        $data = [
            'page' => [
                'page' => $params['page'],
                'perPage' => $params['perPage'],
                'total' => 0,
                'totalPage' => 0,
            ],
            'list' => [],
        ];
        $where = [];
        $option = ['orderByRaw' => 'id desc', 'perPage' => $params['perPage'], 'page' => $params['page'], 'pageName' => 'page'];

        if (isset($params['user']['roleId']) && $params['user']['roleId']){
            $data_permission=Db::table('rbac_role')->where('id',$params['user']['roleId'])->value('data_permission');
            $data_permission=$data_permission?json_decode($data_permission,true):[];
            $data_permission=empty($data_permission)?[]:reset($data_permission);
            //只看个人
            if (isset($data_permission['permissionType']) && $data_permission['permissionType']==2){
                $where[] = ['work_employee_id', '=', $params['user']['workEmployeeId']];
            }
            if (isset($data_permission['permissionType']) && $data_permission['permissionType']==1){
                $department_id=Db::table('work_employee_department')->where('employee_id',$params['user']['workEmployeeId'])->value('department_id');
                if ($department_id){
                    $employee_ids=Db::table('work_employee_department')->where('department_id',$department_id)->select('employee_id')->get();
                    $employee_ids=empty($employee_ids)?[]:array_column($employee_ids->toArray(),'employee_id');
                    $where[] = ['work_employee_id', 'in', $employee_ids];
                }
            }
        }

        if ($params['mobile']) {
            $where[] = ['mobile', '=', $params['mobile']];
        }
        $where[] = ['is_failure', '=', $params['is_failure']];
        if ($params['b2bClientKeyword']) {
            $where[] = ['id', '=', $params['b2bClientKeyword']];
        }
        if (isset($params['is_cooperate']) && is_numeric($params['is_cooperate'])) {
            $where[] = ['is_cooperate', '=', $params['is_cooperate']];
        }
        if ($params['enterpriseKeyword']) {
            $where[] = ['enterprise_name', 'LIKE', '%' . trim($params['enterpriseKeyword']) . '%'];
        }
        if ($params['b2bSalesmanName']) {
            $where[] = ['b2b_salesman_name', 'LIKE', '%' . $params['b2bSalesmanName'] . '%'];
        }
        if ($params['b2bManagerName']) {
            $where[] = ['b2b_manager_name', 'LIKE', '%' . $params['b2bManagerName'] . '%'];
        }
        if (isset($params['level']) && $params['level']!=='') {
            $where[] = ['level', '=', $params['level']];
        }
        if (isset($params['startAllocateTime']) && !empty($params['startAllocateTime']) && isset($params['endAllocateTime']) && !empty($params['endAllocateTime'])) {
            $where[] = ['allocate_time', '>=', $params['startAllocateTime']];
            $where[] = ['allocate_time', '<', $params['endAllocateTime']];
        }
        $follows = Db::table('client_follow_record')
            ->when(!empty($params['startFollowupTime']) && !empty($params['endFollowupTime']),function ($query)use($params){
                $query ->where('followed_at', '>=', $params['startFollowupTime'])
                    ->where('followed_at', '<', $params['endFollowupTime']);
            })
            ->select([
                Db::raw('SUBSTRING_INDEX(GROUP_CONCAT(client_id ORDER BY id DESC SEPARATOR ","),",",1) AS client_id'),
                Db::raw('SUBSTRING_INDEX(GROUP_CONCAT(followed_at ORDER BY id DESC SEPARATOR ","),",",1) AS followed_at'),
            ])
            ->groupBy(['client_id'])
            ->get()
            ->toArray();
        $followId = empty($follows) ? [] : array_column($follows, 'client_id');
        $follows = empty($follows) ? [] : array_column($follows, null, 'client_id');
        if (isset($params['startFollowupTime']) && !empty($params['startFollowupTime']) && isset($params['endFollowupTime']) && !empty($params['endFollowupTime'])) {
            $where[] = ['id', 'in', $followId];
        }
        if (isset($params['isFollow']) && is_numeric($params['isFollow'])) {
            if ($params['isFollow']==1){
                $where[] = ['id', 'in', $followId];
            }
            if ($params['isFollow']==0){
                $where[] = ['id', 'not in', $followId];
            }
        }
        if (isset($params['province']) && !empty($params['province'])) {
            $where[] = ['province', '=', $params['province']];
        }
        if (isset($params['city']) && !empty($params['city'])) {
            $where[] = ['city', '=', $params['city']];
        }
        if (isset($params['district']) && !empty($params['district'])) {
            $where[] = ['district', '=', $params['district']];
        }
        if (!empty($params['isBinding'])) {
            $clients = Db::table('client_contact_pivot')
                ->groupBy([
                    'client_id',
                ])
                ->having('count', '>', 1)
                ->select([
                    Db::raw('COUNT(*) as count'),
                    'client_id',
                ])->get();
            $clients || $clients = collect([]);
            $clients = $clients->toArray();
            $clientId = array_column($clients, 'client_id');
            if (!empty($clientId)) {
                $where[] = ['id', 'in', $clientId];
            }
        }
        $res = $this->clientService->getClientList($where, ['*'], $option);
        if (empty($res['data'])) {
            return $data;
        }
        foreach ($res['data'] as &$value) {
            $value['followedAt'] = '';
            $value['isFollowed'] = false;
            $value['isFollowed_string'] = '否';
            if (isset($follows[$value['id']])) {
                $value['followedAt'] = $follows[$value['id']]->followed_at;
                $value['isFollowed'] = true;
                $value['isFollowed_string'] = '是';
            }
            $province = Db::table('district')->where('id', $value['province'])->value('name');
            $city = Db::table('district')->where('id', $value['city'])->value('name');
            $district = Db::table('district')->where('id', $value['district'])->value('name');
            $value['preAddress'] = $province . $city . $district;

            $value['contactName'] =Db::table('client_phone')
                ->where('client_id',$value['id'])
                ->pluck('name')->toArray();
            $value['contactName'] =  $value['contactName']?implode(',',$value['contactName']):'';
            $client= $this->clientService->getClientById((int)$value['id']);
            $value['contactName'] =$value['contactName']?$value['contactName']:$client['enterpriseName'];

            $value['labelNames']=Db::table('client_label_relation as r')
                ->join('client_label as label','label.id','=','r.client_label_id')
                ->where('r.client_id', $value['id'])
                ->pluck('label.name');
            $value['labelNames'] || $value['labelNames']=collect([]);
            $value['labelNames']=$value['labelNames']->toArray();
        }
        unset($value);
        $data['list'] = $res['data'];
        $data['page']['total'] = $res['total'];
        $data['page']['totalPage'] = $res['last_page'];
        return $data;
    }

}
